package com.zhiyou100.util;

import cn.hutool.core.lang.Console;
import org.hibernate.HibernateException;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

/**
 * hibernate 工具类
 *
 * @author yang
 * @version 1.0.0
 * @date 2020-09-17 17:43
 */
public class HibernateUtil implements AutoCloseable {

    private static final SessionFactory SESSION_FACTORY = buildSessionFactory();

    private static SessionFactory buildSessionFactory() {
        try {
            // Create the SessionFactory from hibernate.cfg.xml
            return new Configuration().configure().buildSessionFactory();
        } catch (Throwable ex) {
            // Make sure you log the exception, as it might be swallowed
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static SessionFactory getSessionFactory() {
        return SESSION_FACTORY;
    }

    @Override
    public void close() throws Exception {
        Console.error("我关闭了！！！！！！！！！！！！！！！！！！！！！！！！！！");
        if (SESSION_FACTORY != null) {
            try {
                SESSION_FACTORY.close();
            } catch (HibernateException e) {
                throw new RuntimeException("SessionFactory 关闭失败！");
            }
        }
    }
}
